package com.aliware.tianchi;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.LoadBalance;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author daofeng.xjf
 *
 * 负载均衡扩展接口
 * 必选接口，核心接口
 * 此类可以修改实现，不可以移动类或者修改包名
 * 选手需要基于此类实现自己的负载均衡算法
 */
public class UserLoadBalance implements LoadBalance {
    private static LoadBalanceManager LM = new LoadBalanceManager();
    private static LoadBalanceHelper lbh = new LoadBalanceHelper();

    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        Invoker result = null;
        //String invo = LM.getInvoker();
        String invo = lbh.getInvoker();
        for (int i = 0; i < invokers.size(); i++)
        {
            Invoker invoker = invokers.get(i);
            int port = invoker.getUrl().getPort();
            if (port == 20880) //small
            {
                if (invo == "small") {
                    result = invoker;
                    LoadBalanceHelper.CurrentSmall.put(invoker.hashCode(), new Date());
                    break;
                }
            }else if (port == 20870) //medium
            {
                if (invo == "medium") {
                    result = invoker;
                    LoadBalanceHelper.CurrentMedium.put(invoker.hashCode(), new Date());
                    break;
                }
            }else if (port == 20890) //large
            {
                if (invo == "large") {
                    result = invoker;
                    LoadBalanceHelper.CurrentLarge.put(invoker.hashCode(), new Date());
                    break;
                }
            }
        }
        return  result;

        //return invokers.get(ThreadLocalRandom.current().nextInt(invokers.size()));
    }
}
